<template>
  <a-drawer
      v-model:visible="vdata.drawerVisible"
      :mask-closable="false"
      title="绑定设备"
      :body-style="{ paddingBottom: '80px' }"
      width="40%"
      class="drawer-width"
      @close="onClose"
  >
    <a-form ref="infoFormModel" :model="vdata.saveObject" layout="horizontal" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <!--         <a-col v-if="vdata.saveObject.provider=='cmf'" :span="24">
                  <a-form-item label="设备名称" name="deviceName">
                    <a-input v-model:value="vdata.saveObject.deviceName" placeholder="请输入设备名称" />
                  </a-form-item>
                </a-col>-->
        <a-col :span="24">
          <a-form-item label="绑定状态：">
            <a-space>
              {{ vdata.saveObject.bindState == 1 ? '已绑定' : '未绑定' }}
              <a-button type="primary" @click="showSelectModal">{{ vdata.saveObject.bindState == 1 ? '重新选择' : '选择商户信息' }}</a-button>
            </a-space>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.showBindInfo" :span="24">
          <a-form-item label="商户号：">
            <span>{{ vdata.saveObject.mchNo }}</span>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.showBindInfo && vdata.isSelectMchApp" :span="24">
          <a-form-item label="应用：">
            <span>{{ vdata.saveObject.appId }}</span>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.showBindInfo" :span="24">
          <a-form-item label="门店：">
            <span>{{ vdata.saveObject.storeId }}</span>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject.provider=='cmf'" :span="24">
          <a-form-item label="选择商户区域" name="areaMch">
            <a-cascader v-model:value="vdata.saveObject.areaMch" :options="areaOptions" placeholder="请选择商户区域" >
              <template #displayRender="{ labels, selectedOptions }">
                <span v-for="(label, index) in labels" :key="selectedOptions[index].value">
                  <span v-if="index === labels.length - 1">
                    {{ label }}
                  </span>
                  <span v-else>{{ label }} /</span>
                </span>
              </template>
            </a-cascader>
          </a-form-item>
          <a-form-item label="选择萤火虫插件" name="deviceUid">
            <a-cascader v-model:value="vdata.saveObject.deviceUid" :options="yhcOptions" placeholder="请选择萤火虫插件" >
              <template #displayRender="{ labels, selectedOptions }">
                <span v-for="(label, index) in labels" :key="selectedOptions[index].value">
                  <span v-if="index === labels.length - 1">
                    {{ label }}
                  </span>
                  <span v-else>{{ label }} /</span>
                </span>
              </template>
            </a-cascader>
          </a-form-item>
          <a-space>
            <a-button type="primary" @click="deviceBinding">初始化绑定</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc"><check-outlined />保存</a-button>
    </div>

    <JeepayModelMchList ref="jeepayModelMchListRef" :showType="vdata.isSelectMchApp ? 'MCH_APP_STORE' : 'MCH_STORE'" :mchNoAndName="true" @selectFinishFunc="selectFinishFunc" />
  </a-drawer>
</template>

<script lang="ts" setup>
import {API_URL_STORE_DEVICE, req, $bindDevice, $initialMch} from '@/api/manage'
import { defineProps, reactive, ref, getCurrentInstance } from 'vue'
import yhcPlusList from './yhcPlusSelect.json'
import areaMchList from './areaMchSelect.json'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
import type { CascaderProps } from 'ant-design-vue'
const yhcOptions: CascaderProps['options'] = yhcPlusList
const areaOptions: CascaderProps['options'] = areaMchList

const props = defineProps({
  callbackFunc: { type: Function, default:null }
})

const infoFormModel = ref()
const jeepayModelMchListRef = ref()

const  vdata = reactive({
  storeList: [] as any, // 门店列表
  btnLoading: false,
  showBindInfo: false, // 显示绑定信息
  saveObject: {} as any, // 数据对象
  isSelectMchApp: false, // 绑定时 是否选择商户应用
  recordId: null, // 更新对象ID
  agentNo: null, // 已划拨的代理商号
  drawerVisible: false // 是否显示弹层/抽屉
}) as any

function show (record: any) { // 弹层打开事件

  if (infoFormModel.value != undefined) {
    infoFormModel.value.resetFields()
  }

  vdata.recordId = record.deviceId
  vdata.isSelectMchApp = record.deviceType != 1 && record.deviceType != 2
  if ((record.provider == 'zw' || record.provider == 'yly') && record.deviceType == 2) {
    vdata.isSelectMchApp = true
  }

  vdata.agentNo = record.agentNo
  vdata.drawerVisible = true


  req.getById(API_URL_STORE_DEVICE, vdata.recordId).then((res: any) => {
    if(res){
      vdata.saveObject = res

      if (vdata.saveObject.bindState == 1) {
        vdata.showBindInfo = true
      } else {
        vdata.showBindInfo = false
        vdata.saveObject.storeId = ''
      }
    }

  })
}

function  handleOkFunc () { // 点击【确认】按钮事件
  infoFormModel.value.validate().then((valid: any) =>{
    vdata.btnLoading = true

    const { deviceId, mchNo, appId, storeId,deviceUid,areaMch,provider } = vdata.saveObject
    if (!storeId) {
      $infoBox.message.error('请选择门店')
      return
    }
    if(provider=='cmf'){
      if (!areaMch) {
        $infoBox.message.error('请选择商户所在区域')
        return
      }
      if (!deviceUid) {
        $infoBox.message.error('请选择萤火虫插件')
        return
      }
    }

    $bindDevice(vdata.recordId, { deviceId, mchNo, appId, storeId,areaMch }).then((res: any) => {
      successFunc('修改成功')
    }).catch((err: any) => {
      vdata.btnLoading = false
    })
  })
}

function successFunc(e: string) { // 新增/更新成功
  vdata.btnLoading = false
  $infoBox.message.success(e)
  props.callbackFunc()
  vdata.drawerVisible = false
}

function deviceBindingSuccess(e: string) { // 新增/更新成功
  vdata.btnLoading = false
  $infoBox.message.success(e)
  props.callbackFunc()
}

// 选择商户、门店弹窗
function showSelectModal(){
  jeepayModelMchListRef.value.show({ agentNo: vdata.agentNo })
}

// 选择商户、门店完成
function selectFinishFunc(selectArray){

  if(!selectArray[0] || !selectArray[2]){
    return $infoBox.message.error('选择信息不完整！')
  }
  if (vdata.isSelectMchApp && !selectArray[1]) {
    return $infoBox.message.error('选择信息不完整！')
  }

  vdata.showBindInfo = true

  vdata.saveObject.mchNo = selectArray[0]
  vdata.saveObject.appId = selectArray[1]
  vdata.saveObject.storeId = selectArray[2]

  jeepayModelMchListRef.value.close()

}

// 初始化商户设备
function deviceBinding(){
  const { deviceId, mchNo, appId, storeId, areaMch, deviceUid} = vdata.saveObject
  if (!storeId) {
    $infoBox.message.error('请选择门店')
    return
  }
  $initialMch(vdata.recordId, { deviceId, mchNo, appId, storeId, areaMch,deviceUid}).then((res: any) => {
    deviceBindingSuccess('操作成功')
  })
}

function  onClose () { // 关闭抽屉
  vdata.drawerVisible = false
}

const value = ref<string[]>([])
defineExpose({
  show
})
</script>
